<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.teacherName"
        placeholder="老师姓名"
        style="width: 200px;"
        clearable
      />
      <el-select
        v-model="listQuery.orgId"
        placeholder="所属校区"
        clearable
        style="width: 180px"
        class="filter-item1"
      >

        <el-option
          v-for="option in orgList"
          :key="option.key"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        >{{ $t("table.search") }}</el-button
      >
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
        >{{ $t("table.add") }}</el-button
      >
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="老师姓名" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.teacherName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="老师性别" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.teacherGender | sexNameFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="老师手机号码" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.teacherPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属校区" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.organizationName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="" align="center">
        <template slot-scope="scope">
          <span>{{
            scope.row.createTime | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="900px">
      <el-form
        ref="userForm"
        :model="userForm"
        :rules="rules"
        class="userForm"
        style=" margin-left:0px;"
        label-position="left"
      >

        <el-row :gutter="10" >
          <el-col :span="8">
            <el-form-item label="老师姓名" prop="teacherName">
              <el-input
                v-model="userForm.teacherName"
                placeholder="请输入老师姓名"
                maxlength="32"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="老师手机号码" prop="teacherPhone">
              <el-input
                v-model="userForm.teacherPhone"
                placeholder="请输入老师手机号码"
                maxlength="32"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="老师性别" prop="teacherGender">
              <el-select
                v-model="userForm.teacherGender"
                placeholder="请选择老师性别"
                style="width:100%"
              >
                <el-option label="男" value="M"></el-option>
                <el-option label="女" value="F"></el-option>
                <el-option label="未知" value="X"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10" >
          <el-col :span="8">
            <el-form-item
              v-for="(audition, index) in userForm.teaCourseList"
              :label="'所属校区-' + (index+1)"
              :key="audition.key"
              :prop="'teaCourseList.' + index + '.orgId'"
              :rules="{
      required: true, message: '请选择所属校区', trigger: 'change'
    }"
            >
              <el-select
                v-model="audition.orgId"
                clearable
                placeholder="请选择所属校区"
                style="width:100%"
                @change="handleOrgChange(audition)"
              >
                <el-option
                  v-for="option in orgList"

                  v-show="isSelect(option.value,audition.orgId)"
                  :key="option.key"
                  :label="option.label"
                  :value="option.value"

                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              v-for="(audition, index) in userForm.teaCourseList"
              :label="'教授课程-' +(index+1)"
              :key="audition.key"
              :prop="'teaCourseList.' + index + '.courseIdList'"
              :rules="{
      required: true, message: '请选择所教授课程', trigger: 'change'
    }"
            >
              <el-select
                v-model="audition.courseIdList"
                multiple
                placeholder="请选择所教授课程"
                collapse-tags
                style="width:100%"
              >
                <el-option-group
                  v-for="group in teacherOptionGroups[index]"
                  :key="group.label"
                  :label="group.label"
                >
                  <el-option
                    v-for="item in group.children"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
<!--            <el-form-item-->
<!--              v-for="(audition,index) in userForm.teaCourseList"-->
<!--              :disabled="index===0"-->
<!--              :label="'操作'"-->
<!--              :key="audition.key"-->
<!--            >-->
<!--              <el-button @click.prevent="removeTeaCourse(audition)" >删除</el-button>-->
<!--            </el-form-item>-->
            <el-form-item
              v-for="(audition,index) in userForm.teaCourseList"

              :label="'操作'"
              :key="audition.key"
            >
              <el-button :disabled="index===0" style="width:100px" @click.prevent="removeTeaCourse(audition)" >删除</el-button>
<!--              <el-select-->
<!--                multiple-->
<!--                v-model="audition.courseIdList"-->
<!--                placeholder="请选择"-->
<!--                style="width:100%"-->
<!--              >-->
<!--                <el-option-group-->
<!--                  v-for="group in teacherOptionGroups[index]"-->
<!--                  :key="group.label"-->
<!--                  :label="group.label"-->
<!--                >-->
<!--                  <el-option-->
<!--                    v-for="item in group.children"-->
<!--                    :key="item.value"-->
<!--                    :label="item.label"-->
<!--                    :value="item.value"-->
<!--                  ></el-option>-->
<!--                </el-option-group>-->
<!--              </el-select>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-button @click="addTeaCourse" >新增所属校区及教授课程</el-button>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("table.cancel")
        }}</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          :loading="submitLoading"
          type="primary"
          @click="createData"
          >{{ $t("table.confirm") }}</el-button
        >
        <el-button v-else :loading="submitLoading" type="primary" @click="updateData">{{
          $t("table.confirm")
        }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchTeacherList,
  createTeacher,
  deleteTeacher,
  updateTeacher
} from "@/api/business/teacher";

import { fetchOrg,fetchCourse } from "@/api/clue";

import waves from "@/directive/waves"; // 水波纹指令
import { parseTime } from "@/utils";

import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

export default {
  name: "UserTable",
  components: { Pagination },
  directives: {
    waves
  },
  filters: {

    sexNameFilter(sex) {
      const sexNameMap = {
        M: "男",
        X: "保密",
        F: "女"
      };
      return sexNameMap[sex];
    }
  },
  data() {
    const validateUserAccount = (rule, value, callback) => {

      const arr = this.userForm.teaCourseList
      const result = arr.some(function(item) {
        if (item.orgId == value) {
          return true;
        }
      })
      if(result){//则包含该元素}
        callback(new Error("请不要重复"));
      } else {
        callback();
      }
    };
    return {
      tableKey: 0,
      orgList: null,
      clueCourIdOptions: [],
      teacherOptionGroups: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 20,
        teacherName: null,
        orgId: null
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "添加"
      },
      userForm: {
        teacherId: "",
        teacherName: "",
        teacherPhone:'',
        teacherGender:'',
        orgId: "",
        teaCourseList: []
      },
      rules: {
        teacherName: [
          { required: true, message: "请输入老师姓名", trigger: "blur" },
          { max: 16, message: "请不要超过 16 个字符", trigger: "blur" }
        ],
        orgId: [
          { required: true, message: "请选择所属校区", trigger: "change" }
        ]
      },
      moreNotifyOjbectRules: {
        moreNotifyOjbectName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const arr = this.userForm.teaCourseList
              const result = arr.some(function(item) {
                if (item.orgId === value) {
                  return true;
                }
              })
              if(result){//则包含该元素}
                callback(new Error("请不要重复"));
              } else {
                callback();
              }
              // if (value.length > 15 || value.length < 2) {
              //   callback(new Error('长度必须为2~8个字符'))
              // } else {
              //   var reg = new RegExp("[`~!@#$^&*()=|{}':',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
              //   if (reg.test(value)) {
              //     callback(new Error('不能含有特殊字符'))
              //   } else {
              //     callback()
              //   }
              // }
            },
            trigger: 'change'
          }
        ],
        moreNotifyOjbectEmail: [{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getRoleList();

  },
  methods: {

    isSelect(id,currentId){
      if(currentId === id){
        return true
      }
      for(let i in this.userForm.teaCourseList){
        debugger
        if(this.userForm.teaCourseList[i].orgId === id){
          return false
        }
      }
      return true
    },
    getList() {
      this.listLoading = true;
      fetchTeacherList(this.listQuery).then(response => {
        this.list = response.data;
        this.total = response.count;
        this.listLoading = false;
      });
    },
    getRoleList() {
      this.listLoading = true;
      const queryMethod = "queryTeacher"
      fetchOrg(queryMethod).then(response => {
        this.orgList = response.data;
        this.listLoading = false;
      });
    },
    //课程（校区Id）
    getCourseOptions(orgId) {
      fetchCourse(orgId).then(response => {
        this.clueCourIdOptions = response.data;
      });
    },
    handleFilter() {
      this.listQuery.current = 1;
      this.getList();
    },
    resetUserForm() {
      this.userForm = {
        teacherId: "",
        teacherName: "",
        orgId: "",
        teaCourseList:[{key: Date.now()}]
      };
    },
    handleCreate() {
      this.resetUserForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["userForm"].clearValidate();
      });
    },
    removeTeaCourse(item) {
      var index = this.userForm.teaCourseList.indexOf(item);
      if (index !== -1) {
        this.userForm.teaCourseList.splice(index, 1);
      }
    },
    addTeaCourse() {
      this.userForm.teaCourseList.push({
        key: Date.now(),
        courseIdList:[]
      });
    },
    handleOrgChange(teaCourse){


      //this.getCourseOptions(teaCourse.orgId);
      var index = this.userForm.teaCourseList.indexOf(teaCourse);
      //根据课程id去查询老师
      //console.table(audition)
      debugger
      fetchCourse(teaCourse.orgId).then(
        response => {
          //this.teacherOptions = response.data;
          debugger
          this.teacherOptionGroups.splice(index, 1, response.data);
        }
      );

      //audition.teacherId = null;
      if (teaCourse.courseIdList.length>0) {
        teaCourse.courseIdList = [];
       }


    },
    createData() {
      this.$refs["userForm"].validate(valid => {
        if (valid) {
          this.submitLoading = true
          createTeacher(this.userForm).then(() => {
            this.dialogFormVisible = false
            this.submitLoading = false
            this.$message({
              message: "创建成功",
              type: "success"
            })
            this.getList()
          }).catch(err => {
            this.submitLoading = false
          })
        }
      });
    },
    handleUpdate(row) {
      this.userForm = Object.assign({}, row); // copy obj
      for (var i = 0; i < this.userForm.teaCourseList.length; i++) {
        var audition = this.userForm.teaCourseList[i];
        fetchCourse(audition.orgId).then(
          response => {
            //this.teacherOptions = response.data;
            this.teacherOptionGroups.splice(i, 1, response.data);
          }
        );
      }

      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["userForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["userForm"].validate(valid => {
        if (valid) {
          this.submitLoading = true
          updateTeacher(this.userForm).then(() => {
            this.dialogFormVisible = false
            this.submitLoading = false
            this.$message({
              message: "更新成功",
              type: "success"
            });
            this.getList()
          }).catch(err => {
            this.submitLoading = false
          })
        }
      });
    },
    handleDelete(row) {
      this.$confirm(
        "此操作将永久删除该数据：" + row.teacherName + ", 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.listLoading = true;
          deleteTeacher(row.teacherId).then(() => {
            this.listLoading = false;
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            const index = this.list.indexOf(row);
            this.list.splice(index, 1);
          }).catch(err => {
            this.listLoading = false
          })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "createTime") {
            return parseTime(v[j]);
          } else if (j === "userSex") {
            return this.$options.filters["sexNameFilter"](v[j]);
          } else if (j === "userStatus") {
            return this.$options.filters["statusNameFilter"](v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    repeatOrgId(){

    }
  }
};
</script>
